package com.qf.Listener.simple;

import com.rabbitmq.client.Channel;
import com.sun.tracing.dtrace.Attributes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 *
 */

@Component
@RabbitListener(queues = {"simple"})
public class SimpleMessageLis {
    @Autowired
    StringRedisTemplate redisTemplate;

    @RabbitHandler
    public void consum(String msg, Channel channel, Message message) throws IOException {
        String messageId = (String) message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");;
        //serIfAbsent相当于redis中的setnx 0,1
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(messageId, "0", 10, TimeUnit.MINUTES);
        //aBoolean 为true，没有id，正常消费
        if(aBoolean){
            try {
                System.out.println("消息队列中的消息:"+msg);
                //执行成功
                /**
                 * 参数1：队列消息的唯一标识
                 * 参数2：是否批量处理
                 */
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (Exception e) {
                e.printStackTrace();
                //出现异常
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }

        }else{
            //aboolean为false，说明redis已经存在id，
            //判断messgeId对应的value是0，还是1， 是0则正在消费，是1则消费成功，手动ack
            String s = redisTemplate.opsForValue().get(messageId);
            if("1".equalsIgnoreCase(s)){
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                redisTemplate.delete(messageId);
            }
        }

    }
}
